package translateUi
{
	import com.utils.RegUtil;
	
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.events.TimerEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.text.TextField;
	import flash.utils.Timer;
	
	import spark.components.Label;
	
	import utils.StringTool;
	
	
	/**
	 * 将转换好的语言，替换进代码里。
	 */
	public class LangReplaceUi
	{
		public static var printMsg:Label;
		public static var exportUrl:String;
		
		private var _path:String;
		private var _path2:String;
		private var _cfgStream:FileStream;
		private var _urlLoader:URLLoader;
		private var _timer:Timer;
		private var _isChange:Boolean;
		
		public function LangReplaceUi()
		{
			_timer = new Timer(1000);
		}
		public function doLoad(path:String):void
		{
			//"C:\Users\Administrator\Desktop\ani原始\21000\bg_tiles\1.mp"
			
			_path = path;
			_path2 = path.replace(".ui", "-222.ui");
			
			loadData();
		}
		private function loadData():void
		{
			var request:URLRequest = new URLRequest(_path);
			_urlLoader = new URLLoader();
			_urlLoader.addEventListener(Event.COMPLETE, onComplete1);
			_urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onLoadError1);
			_urlLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onLoadError2);
			_urlLoader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoadError3);
			_urlLoader.data = null;
			_urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
			_urlLoader.load(request);
			
		}
		/**
		 * 注意，以下转换，只转换logic、modules包里的内容，其它的不要转换。
		 */
		private function onComplete1(e:Event):void
		{
			_urlLoader.removeEventListener(Event.COMPLETE, onComplete1);
			_urlLoader.removeEventListener(IOErrorEvent.IO_ERROR, onLoadError1);
			_urlLoader.removeEventListener(HTTPStatusEvent.HTTP_STATUS, onLoadError2);
			_urlLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onLoadError3);
			
			_isChange = false;
			var content:String = (_urlLoader.data);
			if(!content){
				return;
			}
			_urlLoader.close();
			
			var jsonObj:Object = JSON.parse(content);
			findText(jsonObj);
			
			var newStr:String = JSON.stringify(jsonObj);
			
			if(!_isChange || newStr == content){
				//不需要操作
				return;
			}
			
			var rootFile:File = new File();
			var fl:File = rootFile.resolvePath(_path2);
			
			try
			{
				_cfgStream = new FileStream();
				_cfgStream.open(fl, FileMode.WRITE);
				_cfgStream.writeUTFBytes(newStr);
				_cfgStream.close();
				
				_timer.addEventListener(TimerEvent.TIMER, onTimer2);
				_timer.start();
			}
			catch(e:Error)
			{
				throw new Error(e.getStackTrace());
			}
			
		}
		private function findText(obj:Object):void
		{
			for(var key:* in obj){
				if(!(obj[key] is String) && !(obj[key] is int)){
					findText(obj[key]);
				}
				else if(key == "label" || key == "text" || key == "labels"){
					var content:String = obj[key];
					var arr:Array;
					if(LangReplaceUiMan.ins.replaceType == 4){
						arr = content.match(/[\uAC00-\uD7A3]+/g);//韩语
					}
					else{
						arr = content.match(/[\u4e00-\u9fa5]+/g);
					}
					if(arr.length){//有中文
						
						if(content.indexOf("捐献和帮会经验均满足要求才能") != -1){
							trace("jjjjjjjjj");
						}
						if(LangReplaceUiMan.ins.replaceType == 4){
							arr = content.match(/[\uAC00-\uD7A3， ,]+/g);//韩语
						}
						else{
							arr = content.match(/[\u4e00-\u9fa5， ,]+/g);
						}
						var keyStr:String = "";
						var keyIndex:int = 0;
						if(content.indexOf(arr[0]) != 0){
							keyStr += "{0}";
							keyIndex ++;
						}
						for(var j:int=0; j<arr.length; j++){
							if(j == arr.length - 1){
								keyStr += arr[j];
							}
							else{
								//								if(arr[j].indexOf(" ") != -1){
								if(arr[j] == " "){
									keyStr += arr[j];
								}
								else{
									keyStr += arr[j] + "{"+keyIndex+"}";
									keyIndex ++;
								}
							}
						}
						
						var langDic:Object = LangReplaceUiMan.ins.langDic;
						var langObj:Object = langDic[keyStr];
						if(langObj && StringTool.trim(langObj.target)){
							
							_isChange = true;
							var replaceArr:Array;
//							if(LangReplaceUiMan.ins.replaceType == 3){
//								replaceArr = langObj.target.match(/[\uAC00-\uD7A3， ,]+/g);//韩语
//							}
//							else{
//								replaceArr = langObj.target.match(/[\u4e00-\u9fa5， ,]+/g);
//							}
							arr = keyStr.split(/{[0-9]+}/g);
							replaceArr = langObj.target.split(/{[0-9]+}/g);
							
							var lineStr:String = "";
							var index4:int = 0;
							var index5:int = 0;
							for(var h:int=0; h<arr.length; h++){
								if(!arr[h]){
									continue;
								}
								var addLen:int = arr[h].length;
								index5 = content.indexOf(arr[h], index4);
								if(index5 == -1){//说明 空格 连接错误了。
									var tempArr:Array = arr[h].match(/[\u4e00-\u9fa5]+/g);
									index5 = content.indexOf(tempArr[0], index4);
									addLen = tempArr[0].length;
								}
								lineStr += content.substring(index4, index5);
								lineStr += replaceArr[h];
								
								index4 = index5 + addLen;
								
								if(h == arr.length-1){
									lineStr += content.substring(index4);
								}
							}
							obj[key] = lineStr;
							
//							obj[key] = langObj.target;
						}
					}
				}
			}
		}
		
		
		private function onTimer2(e:TimerEvent):void
		{
			var rootFile:File = new File();
			var fnew:File = rootFile.resolvePath(_path2);
			if(fnew.exists){
				
				_timer.removeEventListener(TimerEvent.TIMER, onTimer2);
				_timer.stop();
				_timer = null;
				
				var rootFile:File = new File();
				var fold:File = rootFile.resolvePath(_path);
				
				fnew.moveTo(fold, true);
			}
		}
		
		private function onLoadError1(e:Event):void
		{
			trace("加载是失败");
		}
		private function onLoadError2(e:HTTPStatusEvent):void
		{
			if(e.status >= 400){
				trace("加载是失败2,url="+e.target.url);
			}
		}
		private function onLoadError3(e:Event):void
		{
			trace("安全沙箱错误");
		}
		
		public static var dicIdCount:int = 0;
	}
}